﻿using System.Net;
using UnityEngine;

namespace Framework
{
    /// <summary>
    /// Unity全局相关的一些帮助函数
    /// </summary>
    public static class UnityHelper
    {
        /// <summary>
        /// 是否是debug包
        /// </summary>
        /// <returns></returns>
        public static bool IsDebugBuild()
        {
            return Application.isEditor || Debug.isDebugBuild;
        }
        
        public static void CsharpGC()
        {
            if (Application.platform == RuntimePlatform.WindowsPlayer)
            {
                //立即压缩大对象堆，项目设置里面.net版本要设置为4.x
                System.Runtime.GCSettings.LargeObjectHeapCompactionMode = System.Runtime.GCLargeObjectHeapCompactionMode.CompactOnce;
            }
            System.GC.Collect();
        }

        
        /// <summary>
        /// 将域名转换成ip
        /// </summary>
        /// <param name="domainOrIp">域名或者ip</param>
        /// <returns></returns>
        public static string ParseDomainToIp(string domainOrIp)
        {
            if (IPAddress.TryParse(domainOrIp, out IPAddress iPAddress))
            {
                return iPAddress.ToString();
            }

            try
            {
                IPAddress[] iPAddresses = Dns.GetHostAddresses(domainOrIp);
                if (null == iPAddresses || iPAddresses.Length <= 0)
                {
                    Logger.LogError($"UnityHelper.ParseDomainToIp, can not parse domain:{domainOrIp} to ip address!");
                    return "";
                }
                return iPAddresses[0].ToString();
            }
            catch (System.Exception exp)
            {
                Logger.LogError($"UnityHelper.ParseDomainToIp, catch Exception: can not parse domain:{domainOrIp} to ip address!");
                Logger.LogException(exp);
            }
            return "";

        }
    }
}
